package com.heima.search.service.impl;


import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
@RequiredArgsConstructor
public class ApUserSearchServiceImpl implements ApUserSearchService {

    private final MongoTemplate mongoTemplate;


    /**
     * 保存用户搜索记录
     * <P>为什么该方法不是从AppThreadLocalUtil去拿用户信息呢？</P>
     * 因为该方法开启了异步线程，是重新开一个线程执行该方法的，所有该方法拿不到用户信息
     * @param userId
     * @param keyword
     */
    @Override
    @Async(value = "taskExecutor")
    public void insert(Integer userId, String keyword) {
        // 1、查询当前mongodb中是否有该条记录
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch userSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        // 2、如果存在 则更新
        if (userSearch != null) {
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }

        // 如果不存在 判断用户的搜素关键词记录是否达到10条
        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());

        Query query1 = Query.query(Criteria.where(("userId")).is(userId));
        query1.with(Sort.by(Sort.Direction.DESC, "createdTime"));

        List<ApUserSearch> apUserSearches = mongoTemplate.find(query1, ApUserSearch.class);
        if (apUserSearches == null || apUserSearches.size() < 10) {
            mongoTemplate.save(apUserSearch);
        }else{
            // 如果达到10条 则替换最早的一条记录
            ApUserSearch lastUserSearch = apUserSearches.get(apUserSearches.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("keyword").is(lastUserSearch.getKeyword())),apUserSearch);
        }




    }


    /**
     * 查询用户的搜索历史记录
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        // 拿到用户id
        ApUser user = AppThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        log.info("用户{}",user);

        Query query=Query.query(Criteria.where("userId").is(user.getId()))
                        .with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }


    /**
     * 删除用户的搜索历史记录 根据id
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearchById(HistorySearchDto dto) {
        //1.检查参数
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3、删除
        Query query = Query.query(Criteria.where("userId").is(user.getId())
                        .and("id").is(dto.getId()));

        mongoTemplate.remove(query, ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
